<?php

namespace apps\admin\controllers;

use enums\DBEnums;;
use Phalcon\Paginator\Adapter\QueryBuilder;
use apps\admin\models\SysDicCategory;
use helpers\TimeUtils;
use apps\admin\models\SystemDic;
use apps\admin\ext\AdminBaseController;
/**
 * @comment( comment = '系统配置' )
 * @author(  author = 'hfc' )
 * @date ( date = '2015-8-28' )
 */
class ConfigController extends AdminBaseController
{
    public function initialize()
    {
        parent::initialize();
    	//$this->checkPlatform();
    }
    
    /**
     * @author( author='Carey' )
     * @date( date = '2016年8月18日' )
     * @comment( comment = '配置分类' )    
     * @method( method = 'categoryAction' )
     * @op( op = '' )    
    */
    public function categoryAction()
    {
        $pageNum = $this->request->getQuery( 'page', 'int' );
        $currentPage = $pageNum ? $pageNum : 1;
        
        
        $builder = $this->modelsManager->createBuilder()
                ->from( 'apps\admin\models\SysDicCategory' )
                ->where( 'delsign=' . DBEnums::DELSIGN_NO . ' ORDER BY sort ASC,uptime DESC' );
        
        $paginator = new QueryBuilder( array(
            'builder' => $builder,
            'limit' => 15,
            'page' => $currentPage
        ));
        $page = $paginator->getPaginate();
        $this->view->page = $page;
       
    }
    
    /**
     * @author( author='Carey' )
     * @date( date = '2016年8月18日' )
     * @comment( comment = '添加分类' )    
     * @method( method = 'addcateAction' )
     * @op( op = '' )    
    */
    public function addcateAction()
    {
        
    }
    
    /**
     * @author( author='Carey' )
     * @date( date = '2016年8月18日' )
     * @comment( comment = '编辑分类' )
     * @method( method = 'editcateAction' )
     * @op( op = '' )
     */
    public function editcateAction()
    {
        $optid = $this->dispatcher->getParam( 'id', 'int' );
        if( !$optid )
           return $this->response->redirect( '/admin/config/addcate' );
        
       $where = array(
            'columns'   => 'id,name,sort,descr,en_name,getter,getter_descr,is_enum',
            'conditions'=> 'id=:optid: and delsign=:del:',
           'bind'       => array( 'optid' => $optid, 'del' => DBEnums::DELSIGN_NO ),
       );
       $res = SysDicCategory::findFirst(  $where );
       if( $res )
       {
           $this->view->res = $res;
           $this->view->pick( 'config/addcate' );
       }
       else
           return $this->response->redirect( '/admin/config/addcate' );
           
    }
    
    /**
     * 生成getter和常量
     * 
     * @return boolean
     */
    public function generateGetterAndEnumsAction()
    {
    	$iID = $this->dispatcher->getParam( 'id', 'int' );
    	
    	try 
    	{
	    	$cateWhere = array(
	    			'columns'   => 'id,name,en_name,getter,getter_descr',
	    			'conditions' => 'delsign=?0 and id=?1',
	    			'bind' => array( DBEnums::DELSIGN_NO, $iID )
	    	);
	    	$objCate = SysDicCategory::findFirst( $cateWhere );
	    	if( !$objCate )
	    	{
	    		$objRet = new \stdClass();
	    		
	    		$objRet->status = 1;
	    		$objRet->msg = '未找到指定的记录';
	    		
	    		echo json_encode( $objRet );
	    		return;
	    	}
	    	
	    	$enumsWhere = array(
	    			'columns'   => 'id,title,key,value',
	    			'conditions' => 'delsign=?0 and cateid=?1',
	    			'bind' => array( DBEnums::DELSIGN_NO, $iID ),
	    			'order' => 'sort asc'
	    	);
	    	$objEnums = SystemDic::find( $enumsWhere );
	    	if( !$objEnums || ( $iEnumsCount = count( $objEnums ) ) <= 0 )
	    	{
	    		$objRet = new \stdClass();
	    		
	    		$objRet->status = 1;
	    		$objRet->msg = '未找到指定的记录';
	    		
	    		echo json_encode( $objRet );
	    		return;
	    	}
	    	
	    	
	    	$strGetterName = $objCate->getter;
	    	$strGetterDescr = $objCate->getter_descr; 
	    	
	    	$selPath = APP_ROOT . 'enums/SelectEnums.php';
	    	
	    	$strSelContent = file_get_contents( $selPath );
	    	$iLastBrace = strrpos( $strSelContent, '}' );
	    	$strSelContent = substr( $strSelContent, 0, $iLastBrace );
	    	
	    	$strGetterHeader = <<<GETTER
/**
	 * $strGetterDescr
	 */    	
	public static function $strGetterName()
	{
		return array(
GETTER;
	    	
	    	
	    	$strGetterFooter = <<<GETTER
	    	
		);
    }
GETTER;
	    	
	    	$bChangeContent = false;
	    	$strGetterContent = '';
	    	//生成常量
	    	foreach( $objEnums as $enum )
	    	{
	    		$strConst = "SEL_" . strtoupper( $objCate->en_name ) . "_" . strtoupper( $enum->key );
	    		$strEnum = <<<ENUMS
   
	/**
	 *	$enum->title
	 */
	const $strConst = $enum->value;

	
ENUMS;
	    		 
		    	if( false === strpos( $strSelContent, $strConst ))
		    	{//不存在则生成常量
		    		$strSelContent = $strSelContent . $strEnum;
		    		$bChangeContent = true;
		    	}
		    	
		    	if( false === strpos( $strSelContent, $objCate->getter ))
		    	{//不存在则生成getter
		    		$strItem = <<<GETTER
		  
		    			self::$strConst => array( 'value' => $enum->value, 'title' => '$enum->title'),
GETTER;
		    		$bChangeContent = true;
		    		
		    		$strGetterContent .= $strItem;
		    	}
		    	 
	    	}
	    	
	    	if( $strGetterContent != '' )
	    	{
	    		$strSelContent .= $strGetterHeader . $strGetterContent . $strGetterFooter;
	    	}
	    	
	    	if( $bChangeContent )
	    	{
	    		file_put_contents( $selPath, $strSelContent . PHP_EOL . '}' );
	    	}
	    	
	    	$objRet = new \stdClass();
	    	 
	    	$objRet->status = 0;
	    	$objRet->msg = '成功生成常量和访问器';
	    	 
	    	echo json_encode( $objRet );
	    	//echo $strSelContent . PHP_EOL . '}';
    	}
    	catch( \Exception $e )
    	{
    		$objRet = new \stdClass();
    		 
    		$objRet->status = 1;
    		$objRet->msg = $e->getMessage();
    		 
    		echo json_encode( $objRet );
    	}
    	
    	$this->view->disable();
    }
    
    /**
     * @author( author='Carey' )
     * @date( date = '2016年8月18日' )
     * @comment( comment = '保存配置分类信息' )    
     * @method( method = 'saveCateAction' )
     * @op( op = 'u' )    
    */
    public function saveCateAction()
    {
        $optid = $this->request->getPost( 'id', 'int' );
        $name  = $this->request->getPost( 'name', 'trim' );
        $descr = $this->request->getPost( 'descr', 'trim' );
        $sort  = $this->request->getPost( 'sort', 'int' );
        $en_name = $this->request->getPost( 'en_name', 'trim' );
        $getter = $this->request->getPost( 'getter', 'trim' );
        $is_enum = $this->request->getPost( 'isenum', 'int' );
        $getter_descr = $this->request->getPost( 'getter_descr', 'trim' );
        if( !$optid )
        {
            $category = new SysDicCategory();
            $category->addtime = $category->uptime = TimeUtils::getFullTime();
            $category->delsign = DBEnums::DELSIGN_NO;
            $category->sort     = $sort;
            $category->name     = $name;
            $category->descr    = $descr;
            $category->en_name = $en_name;
            $category->getter = $getter;
            $category->is_enum = $is_enum;
            $category->getter_descr = $getter_descr;
            
            if( $category->save() )
            {
                return $this->response->redirect( '/admin/config/category' );
            }
            else
            {
                return $this->response->redirect( '/admin/config/addcate' );
            }
        }
        else
        {
            $where = array(
                'conditions'=> 'id=:optid: and delsign=:del:',
                'bind'       => array( 'optid' => $optid, 'del' => DBEnums::DELSIGN_NO ),
            );
            $category = SysDicCategory::findFirst(  $where );
            if( $category )
            {
                $category->uptime = TimeUtils::getFullTime();
                $category->sort     = $sort;
                $category->name     = $name;
                $category->descr    = $descr;
                $category->en_name = $en_name;
                $category->getter = $getter;
                $category->is_enum = $is_enum;
                $category->getter_descr = $getter_descr;
                
                if( $category->save() )
                {
                    return $this->response->redirect( '/admin/config/category' );
                }
                else
                {
                    return $this->response->redirect( '/admin/config/editcate/id/'. $optid );
                }
            }
            else
                return $this->response->redirect( '/admin/config/catrgory' );
        }
        
    }
    
    /**
     * @author( author='Carey' )
     * @date( date = '2016年8月18日' )
     * @comment( comment = '系统配置中心' )    
     * @method( method = 'indexAction' )
     * @op( op = '' )    
    */
    public function indexAction()
    {
        $catId = $this->request->getQuery( 'cateid', 'int' );
        $pageNum = $this->request->getQuery( 'page', 'int' );
        $currentPage = $pageNum ? $pageNum : 1;
        
        $where = 'a.delsign=' . DBEnums::DELSIGN_NO . ' ORDER BY a.uptime desc, c.sort ASC';
        if( $catId && false != $catId  )
            $where = 'a.delsign=' . DBEnums::DELSIGN_NO . ' AND a.cateid='.$catId.' ORDER BY a.uptime desc, c.sort ASC';
        
        $builder = $this->modelsManager->createBuilder()
                    ->columns( 'a.id,a.key,a.value,a.valtype,a.title,a.sort,a.uptime,c.name,c.en_name' )
                    ->addFrom( 'apps\admin\models\SystemDic' , 'a' )
                    ->join( 'apps\admin\models\SysDicCategory' , 'a.cateid = c.id', 'c' )
//                     ->orderBy( 'a.sort' )
                    ->where( $where );
                
        $paginator = new QueryBuilder( array(
            'builder' => $builder,
            'limit' => 15,
            'page' => $currentPage
        ));
        $page = $paginator->getPaginate();
        $this->view->page = $page;
        $this->view->cateId = $catId?$catId:0;
        
        $category = SysDicCategory::getAll();
        $this->view->category = $category;
    }
    
    /**
     * @author( author='Carey' )
     * @date( date = '2016年8月18日' )
     * @comment( comment = '添加配置项' )    
     * @method( method = 'addAction' )
     * @op( op = '' )    
    */
    public function addAction()
    {
        $category = SysDicCategory::getAll();
        
        $this->view->category = $category;
    }
    
    /**
     * @author( author='Carey' )
     * @date( date = '2016年8月18日' )
     * @comment( comment = '编辑配置项' )    
     * @method( method = 'editAction' )
     * @op( op = '' )    
    */
    public function editAction()
    {
        $optid = $this->dispatcher->getParam( 'id', 'int' );
        if( !$optid )
            return $this->response->redirect( '/admin/config/index' );
        
        $where = array(
            'columns'   => 'id,title,key,value,valtype,cateid,descr,sort',
            'conditions'=> 'id=:optid: and delsign=:del:',
            'bind'      => array( 'optid' => $optid, 'del' => DBEnums::DELSIGN_NO ),
        );
        $res = SystemDic::findFirst( $where );
        if( $res )
        {
            $category = SysDicCategory::getAll();
            $this->view->category = $category;
            $this->view->res  = $res;
            
            $this->view->pick( 'config/add' );
        }
        else
            return $this->response->redirect( '/admin/config/add' );
        
    }
    
    /**
     * @author( author='Carey' )
     * @date( date = '2016年8月18日' )
     * @comment( comment = '保存配置项信息' )    
     * @method( method = 'saveAction' )
     * @op( op = '' )    
    */
    public function saveAction()
    {
        $name  = $this->request->getPost( 'name', 'trim' );
        $cateid = $this->request->getPost( 'cateid', 'int' );
        $key   = $this->request->getPost( 'key', 'trim' );
        $valtype = $this->request->getPost( 'valtype', 'int' );
        $value = $this->request->getPost( 'value', 'trim' );
        $descr = $this->request->getPost( 'descr', 'trim' );
        $optid = $this->request->getPost( 'id', 'int' );
        $sort = $this->request->getPost( 'sort', 'int' );
        
        if( !$optid )
        {
            $res = new SystemDic();
            $res->addtime   = $res->uptime = TimeUtils::getFullTime();
            $res->delsign       = DBEnums::DELSIGN_NO;
            $res->descr         = $descr;
            $res->title         = $name;
            $res->key           = $key;
            $res->value         = $value;
            $res->valtype       = $valtype;
            $res->cateid        = $cateid;
            $res->sort 			= $sort;
            
            if( $res->save() )
            {
                return $this->response->redirect( '/admin/config/index' );
            }
            else
            {
                return $this->response->redirect( '/admin/config/add' );
            }
        }
        else
        {
            $where = array(
                'conditions'=> 'id=:optid: and delsign=:del:',
                'bind'      => array( 'optid' => $optid, 'del' => DBEnums::DELSIGN_NO ),
            );
            $res = SystemDic::findFirst( $where );
            if( $res )
            {
                $res->uptime = TimeUtils::getFullTime();
                $res->descr         = $descr;
                $res->title         = $name;
                $res->key           = $key;
                $res->value         = $value;
                $res->valtype       = $valtype;
                $res->cateid        = $cateid;
                $res->sort			= $sort;
                
                if( $res->save() )
                {
                    return $this->response->redirect( '/admin/config/index' );
                }
                else
                {
                    return $this->response->redirect( '/admin/config/edit/id/' . $optid );
                }
            }
            else 
            {
                return $this->response->redirect( '/admin/config/index' );
            }
        }
        
    }

    /**
     * @author( author='Carey' )
     * @date( date = '2016年8月22日' )
     * @comment( comment = '获取关键字 判断是否重复' )    
     * @method( method = 'getkeyAction' )
     * @op( op = '' )    
    */
    public function getkeyAction()
    {
        $key = $this->dispatcher->getParam( 'key', 'trim' );
        
        $objRet = new \stdClass();
        if( !$key )
        {
            $objRet->state = 1;
            $objRet->msg = '参数错误,请刷新后再试..';
            
            echo json_encode( $objRet );
        }
        
        $where = array(
            'columns'   => 'id,key',
            'conditions'=> 'key=:key: and delsign=:del:',
            'bind'      => array( 'key' => $key, 'del' => DBEnums::DELSIGN_NO ),
        );
        $res = SystemDic::count( $where );
        
        var_dump( $res && count( $res ) );
        return true;
        if( $res && count( $res ) > 0  )
        {
            $objRet->state = 0; //存在
        }
        else
        {
            $objRet->state = 1; //不存在
        }
        
        echo json_encode( $objRet );
    }
}
